//
//  TTExtractAddressViewController.m
//  TaoTuo
//
//  Created by admin on 2019/9/29.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTExtractAddressViewController.h"
#import "TTExtractAddressViewCell.h"

static NSString *cellID = @"extract_cell_id";

@interface TTExtractAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, copy) void(^selectBlock)(TTAddressModel *model);

@property (nonatomic, assign) BOOL isChangeAddress;

@property (nonatomic, strong) NSIndexPath *lastIndexPath;

@property (nonatomic, strong) TTAddressModel *selectModel;

@end

@implementation TTExtractAddressViewController

- (instancetype)initWithSelectBlock:(void (^)(TTAddressModel * _Nonnull))selectBlock
{
    if (self == [super init]) {
        self.selectBlock = selectBlock;
    }
    return self;
}

- (instancetype)initWithSelectBlock:(void (^)(TTAddressModel * _Nonnull))selectBlock isChangeAddress:(BOOL)isChangeAddress
{
    if (self == [super init]) {
        self.selectBlock = selectBlock;
        self.isChangeAddress = isChangeAddress;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"提货地址";
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"extract_address" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    // 开通的门店
    NSMutableArray *openArray = [NSMutableArray array];
    for (NSDictionary *openDic in dic[@"Opened"]) {
        TTAddressModel *model = [TTAddressModel modelWithJSON:openDic];
        model.isOpen = YES;
        [openArray addObject:model];
        if ([model.Address isEqualToString:self.addressModel.Address]) {
            model.isSelect = YES;
        }
    }
    // 未开通的门店
    NSMutableArray *unOpenArray = [NSMutableArray array];
    for (NSDictionary *unOpenDic in dic[@"UnOpened"]) {
        TTAddressModel *model = [TTAddressModel modelWithJSON:unOpenDic];
        [unOpenArray addObject:model];
    }
    
    [self.dataArray addObject:openArray];
    [self.dataArray addObject:unOpenArray];
    
    [self.tableView reloadData];
    
    [self addBottomView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = self.dataArray[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *arr = self.dataArray[indexPath.section];
    TTExtractAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:arr[indexPath.row] isChangeAddress:self.isChangeAddress];
    @weakify(self)
    cell.selectBlock = ^(TTExtractAddressViewCell * _Nonnull tCell, TTAddressModel * _Nonnull model) {
        @strongify(self)
        NSIndexPath *inp = [tableView indexPathForCell:tCell];
        [self handelClickCellOrBtnWithIndexPath:inp];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == self.dataArray.count - 1) {
        [self.view makeToast:@"此门店尚未开通，请选择已开通门店" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    
    if (self.isChangeAddress) {
        
        [self handelClickCellOrBtnWithIndexPath:indexPath];
        
        return;
    }
    
    
    NSMutableArray *arr = self.dataArray[indexPath.section];
    if (self.selectBlock) {
        self.selectBlock(arr[indexPath.row]);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)handelClickCellOrBtnWithIndexPath:(NSIndexPath *)indexPath
{
    if (self.lastIndexPath) {
        TTAddressModel *addrModel = self.dataArray[self.lastIndexPath.section][self.lastIndexPath.row];
        addrModel.isSelect = NO;
    }
    
    NSMutableArray *arr = self.dataArray[indexPath.section];
    
    TTAddressModel *model = arr[indexPath.row];
    model.isSelect = YES;
    
    self.lastIndexPath = indexPath;
    
    self.selectModel = model;
    
    [self.tableView reloadData];
    
    if (!self.isChangeAddress) {
        if (self.selectBlock) {
            self.selectBlock(arr[indexPath.row]);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *arr = self.dataArray[indexPath.section];
    return [tableView fd_heightForCellWithIdentifier:cellID cacheByIndexPath:indexPath configuration:^(TTExtractAddressViewCell *cell) {
        [cell setModel:arr[indexPath.row] isChangeAddress:self.isChangeAddress];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == self.dataArray.count - 1) {
        return 30;
    }
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == self.dataArray.count - 1) {
        UILabel *label = [UILabel labelTextCenterWithTitle:@"———— 以下门店尚未开通 ————" color:UIColorHex(999999) fontSize:11];
        label.frame = CGRectMake(0, 0, self.view.width, 30);
        label.backgroundColor = kSeparatorColor;
        return label;
    } else {
        return [UIView new];
    }
    
}

- (void)confirmExchangeClick
{
    if (self.selectBlock) {
        self.selectBlock(self.selectModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBottomView
{
    if (self.isChangeAddress) {
        
        UIButton *bottomBtn = [UIButton createButtonWithTitle:@"确认更换" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(confirmExchangeClick)];
        [self.view addSubview:bottomBtn];
        [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuide);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(45);
        }];
        
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTExtractAddressViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
